//
//  AgentViewController.m
//  housingResources
//
//  Created by YYQ on 2017/6/30.
//  Copyright © 2017年 节操君. All rights reserved.
//

#import "AgentViewController.h"
#import "UIView+Toast.h"

@interface AgentViewController (){
    UIScrollView *baseScrollview;
}

@property (nonatomic, strong) UITextField *nameTF;
@property (nonatomic, strong) UITextField *numTF;
@property (nonatomic, strong) UIImageView *PositiveImgView;
@property (nonatomic, strong) UIImageView *OppositeveImgView;
@property (nonatomic, strong) UIImageView *agentImgView;
@property (nonatomic, strong) UIImageView *agentBackImgView;
@property (nonatomic, strong) UIButton *sendBtn;

@property (nonatomic, strong) NSMutableDictionary *dic1;
@property (nonatomic, strong) NSMutableDictionary *dic2;
@property (nonatomic, strong) NSMutableDictionary *dic3;
@property (nonatomic, strong) NSMutableDictionary *dic4;

@property (nonatomic ,strong) UIImageView *currentImgView;

@end

@implementation AgentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"经纪人认证";
    self.view.backgroundColor = [UIColor whiteColor];

    [self creatView];
    
}

//创建试图
- (void)creatView{
    baseScrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64)];
    baseScrollview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:baseScrollview];
    
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 60 / kScale, 180 / kScale, 60 / kScale)];
    nameLabel.text = @"姓名";
    nameLabel.textAlignment = NSTextAlignmentRight;
    [baseScrollview addSubview:nameLabel];
    
    UILabel *numLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 / kScale, 220 / kScale, 60 / kScale)];
    numLabel.text = @"身份证号码";
    numLabel.textAlignment = NSTextAlignmentRight;
    [baseScrollview addSubview:numLabel];
    
    UILabel *shenLabel = [[UILabel alloc]initWithFrame:CGRectMake(30 / kScale, 300 / kScale, 400 / kScale, 60 / kScale)];
    shenLabel.text = @"上传身份证正反面";
    [baseScrollview addSubview:shenLabel];
    
    [baseScrollview addSubview:self.nameTF];
    [baseScrollview addSubview:self.numTF];
    [baseScrollview addSubview:self.PositiveImgView];
    [baseScrollview addSubview:self.OppositeveImgView];
    [baseScrollview addSubview:self.agentImgView];
    [baseScrollview addSubview:self.agentBackImgView];
    [baseScrollview addSubview:self.sendBtn];
    
    _currentImgView = [[UIImageView alloc]init];
}

- (UITextField *)nameTF{
    if (!_nameTF) {
        _nameTF = [[UITextField alloc]initWithFrame:CGRectMake(200 / kScale, 60 / kScale, kScreenWidth - 240 / kScale, 60 / kScale)];
        _nameTF.placeholder = @"请输入真实姓名";
        
    }
    return _nameTF;
}

- (UITextField *)numTF{
    if (!_numTF) {
        _numTF = [[UITextField alloc]initWithFrame:CGRectMake(240 / kScale, 200 / kScale, kScreenWidth - 260 / kScale, 60 / kScale)];
        _numTF.placeholder = @"请输入身份证";
        
    }
    return _numTF;
}

- (UIImageView *)PositiveImgView{
    if (!_PositiveImgView) {
        _PositiveImgView = [[UIImageView alloc]initWithFrame:CGRectMake(90 / kScale, 400 / kScale, 240 / kScale, 180 / kScale)];
        _PositiveImgView.backgroundColor = [UIColor redColor];
        _PositiveImgView.userInteractionEnabled = YES;
        [_PositiveImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerViewTapAction:)]];
        
        //        UIImageView *addImg = [[UIImageView alloc]initWithFrame:CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>)];
        
    }
    return _PositiveImgView;
}

- (UIImageView *)OppositeveImgView{
    if (!_OppositeveImgView) {
        _OppositeveImgView = [[UIImageView alloc]initWithFrame:CGRectMake(430 / kScale, 400 / kScale, 240 / kScale, 180 / kScale)];
        _OppositeveImgView.backgroundColor = [UIColor redColor];
        _OppositeveImgView.userInteractionEnabled = YES;
        [_OppositeveImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerViewTapAction:)]];
    }
    return _OppositeveImgView;
}

- (UIImageView *)agentImgView{
    if (!_agentImgView) {
        _agentImgView = [[UIImageView alloc]initWithFrame:CGRectMake(90 / kScale, 750 / kScale, 240 / kScale, 180 / kScale)];
        _agentImgView.backgroundColor = [UIColor redColor];
        _agentImgView.userInteractionEnabled = YES;
        [_agentImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerViewTapAction:)]];
    }
    return _agentImgView;
}

- (UIImageView *)agentBackImgView{
    if (!_agentBackImgView) {
        _agentBackImgView = [[UIImageView alloc]initWithFrame:CGRectMake(430 / kScale, 750 / kScale, 240 / kScale, 180 / kScale)];
        _agentBackImgView.backgroundColor = [UIColor redColor];
        _agentBackImgView.userInteractionEnabled = YES;
        [_agentBackImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerViewTapAction:)]];
    }
    return _agentBackImgView;
}

- (UIButton *)sendBtn{
    if (!_sendBtn) {
        _sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _sendBtn.frame = CGRectMake(30 / kScale, 1000 / kScale, kScreenWidth - 60 / kScale, 70 / kScale);
        _sendBtn.titleLabel.font = [UIFont systemFontOfSize:34 / kScale];
        [_sendBtn setTitle:@"提交认证信息" forState:UIControlStateNormal];
        [_sendBtn setBackgroundColor:[UIColor orangeColor]];
        [_sendBtn addTarget:self action:@selector(sendAction:) forControlEvents:UIControlEventTouchUpInside];
        [_sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _sendBtn.layer.cornerRadius = 35 / kScale;
    }
    return _sendBtn;
}

#pragma mark - Action
- (void)headerViewTapAction:(UITapGestureRecognizer *)tap{
    //    LoadHeaderImgViewController *vc = [[LoadHeaderImgViewController alloc]init];
    //    vc.hidesBottomBarWhenPushed = YES;
    //    vc.LoadHeaderImgSuccess = ^(NSString *headerImgUrl) {
    ////        [headerImgV setImage:[UIImage imageNamed:headerImgUrl]];
    //    };
    //    [self.navigationController pushViewController:vc animated:YES];
    _currentImgView = (UIImageView *)[tap view];
    //修改头像
    UIAlertController *severAlert = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleAlert];
    //取消按钮
    UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    [cancelBtn setValue:[UIColor redColor] forKey:@"titleTextColor"];
    //拍照
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [self deployImagePickerController:UIImagePickerControllerSourceTypeCamera];
        } else {
            [self creatAlertForUnsupport:@"相机"];
        }
        
    }];
    //相册选择
    UIAlertAction *photo = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
            [self deployImagePickerController:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
        } else {
            [self creatAlertForUnsupport:@"相册"];
        }
        
    }];
    [severAlert addAction:camera];
    [severAlert addAction:photo];
    [severAlert addAction:cancelBtn];
    [self presentViewController:severAlert animated:YES completion:nil];
    
}

#pragma mark ----- 图片选择器（头像） -----
/** 如果不支持这种选择类型 弹出警告框 */
- (void)creatAlertForUnsupport:(NSString *)str{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"当前设备不支持%@",str] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}
/** 配置imagePickerController */
- (void)deployImagePickerController:(UIImagePickerControllerSourceType)sourceType{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
    imagePickerController.sourceType = sourceType;
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

#pragma mark-UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    [self uploadToServer:image];
}

- (void)uploadToServer:(UIImage *)image{
    
    NSString *urlStr = @"http://120.24.37.227:8081/yjr/api/upload";
    //    NSString *url = CHANGEUSERPHOTO;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDate *now = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[now timeIntervalSince1970]];
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *dic = [userDefault objectForKey:@"userDatas"];
    NSString *myPhone = dic[@"user_phone"];
    
    NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[SaveData getUserToken] forKey:@"token"];
    [params setObject:[SaveData getUserId] forKey:@"linkid"];
    [params setObject:@"yj_pic" forKey:@"ftype"];
    
    //    NSLog(@"imageData:%ld", imageData.length);
    
    //parameters中的参数是文字的参数，constructingBodyWithBlock中的参数是文件，其中的name为文件参数的名称
    
    [manager POST:urlStr parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:imageData name:@"myfiles" fileName:[NSString stringWithFormat:@"%@_%@.jpg", myPhone,timeSp] mimeType:@"image/jpg"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSDictionary *jsonDic = [responseObject objectForKey:@"data"];
        
        if (_currentImgView == _PositiveImgView) {
            _dic1 = [NSMutableDictionary dictionary];
            _dic1 = [jsonDic objectForKey:@"paths"];
        }else if (_currentImgView == _OppositeveImgView){
            _dic2 = [NSMutableDictionary dictionary];
            _dic2 = [jsonDic objectForKey:@"paths"];
        }else if (_currentImgView == _agentImgView){
            _dic3 = [NSMutableDictionary dictionary];
            _dic3 = [jsonDic objectForKey:@"paths"];
        }else if (_currentImgView == _agentBackImgView){
            _dic4 = [NSMutableDictionary dictionary];
            _dic4 = [jsonDic objectForKey:@"paths"];
        }
        
        
        //修改UI
        _currentImgView.image = image;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"upload image failed , because :%@",error.description);
        UIAlertController *severAlert = [UIAlertController alertControllerWithTitle:@"修改失败，请稍后重试" message:nil preferredStyle:UIAlertControllerStyleAlert];
        //取消按钮
        UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"取消");
            
        }];
        [severAlert addAction:cancelBtn];
        [self presentViewController:severAlert animated:YES completion:nil];
    }];
}


- (void)sendAction:(UIButton *)btn{
    if (_nameTF.text.length == 0) {
        [self.view makeToast:@"请输入真实姓名"];
        return;
    }
    if (_numTF.text.length != 18) {
        [self.view makeToast:@"请输入正确的省身份证"];
        return;
    }
    if (_dic1 == nil) {
        [self.view makeToast:@"请上传身份证正面"];
        return;
    }
    if (_dic2 == nil) {
        [self.view makeToast:@"请上传身份证反面"];
        return;
    }
    NSString *str1 = [_dic1 valueForKey:@"filepath"];
    NSString *str2 = [_dic2 valueForKey:@"filepath"];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:_nameTF.text forKey:@"realname"];
    [params setObject:_numTF.text forKey:@"idcard"];
    [params setObject:str1 forKey:@"idcateurl"];
    [params setObject:str2 forKey:@"idcatebackurl"];
    [params setObject:[SaveData getUserToken] forKey:@"token"];
    
    NSString *urlStr = @"isLive";
    
    //    [DataServiece requestWithURLString:urlStr parameters:params type:HttpRequestTypePost success:^(id responseObject) {
    //        NSLog(@"%@",responseObject);
    //        [self.view makeToast:[responseObject valueForKey:@"msg"]];
    //    } failure:^(NSError *error) {
    //        NSLog(@"%@",error);
    //    }];
    
    [DataServiece RequestWithUrlToJson:urlStr params:params finishDidBlock:^(NSURLSessionDataTask *task, id result) {
        NSLog(@"%@",result);
        [self.view makeToast:[result valueForKey:@"msg"]];
    } failuerBlock:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
